package com.heatup.apt.common.util;

import sun.misc.*;

import java.io.*;

/**
 * base64处理工具类
 * <p>
 * <p>
 * Created by blank on 2017/10/27 下午5:10
 */
public class Base64Util {


    //图片转化成base64字符串
    public static String getImgFileToBase64(String imgFilePath) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理

        InputStream in = null;
        byte[] data = null;
        String base64 = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
            //对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            base64 = "data:image/gif;base64," + encoder.encode(data);
            return base64 ;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            File file = new File(imgFilePath);
            boolean delete = file.delete();
            System.err.println("临时文件删除 " + delete);
        }


        return base64 ;//返回Base64编码过的字节数组字符串图片
    }


    //base64字符串转化成图片
    public static boolean generateImage(String imgStr) {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }

            String userHomePath = System.getProperty("user.home");
            String imgPath = userHomePath + File.separator + "222.png";

            //生成jpeg图片
            String imgFilePath = "~/222.jpg";//新生成的图片
            OutputStream out = new FileOutputStream(imgPath);
            out.write(b);
            out.flush();
            out.close();
            System.out.println("生成图片成功...");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        generateImage("iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAABtklEQVR42u2YPY6EMAyFjSgoOUJu\n" +
                "MlxspETKxeAmOQJlCoT32WGYZaVtH6vVpIhIviks+/knI/rbkg/56ySJyKilTpoLPqNtPZVk1X3M\n" +
                "RXdcmlG2ZS4p8hhV6wMWVbdSxhtIEpAnttvIFuCiFKRb4w1E2+VDJLh3rpEjENdoLnDMsV3VSyC+\n" +
                "NhncolnijwwmENhmjhlmD5J9LWukEpi1vHQhtgZdeyrJnqLQhZ3xw3B6h0VSC031ctHZcR/ZRLxI\n" +
                "iDyDG4jKzSVZERBIYkduyLQ+LVw9lejRqeyy5Wl3aJRFYNvSgoTjUTOUSjZBfeh1mJGi3r1gZaQS\n" +
                "FOgFe53WvtTuGh8O8QrVF1cIeoeWd61iEUFabAHlIsJFKFhnnrJIbgkCx6BrQqP2FbnE4gMXmUzE\n" +
                "47O/JkgWsT4R9ShYplE7UkkZfLNBttrlO4N5xJTZLNqtbXbnFM0hvpIL1ecodZkwic9vKdQ2viJj\n" +
                "PV+YJLf6YG8Zq9w+SJCJzfEmDjMQm5z1mkpSGLx/WmigEOUT2DbZ2GLvqjZIMMn5luk9T8ulXjPI\n" +
                "8ZbR2Z+V1jG+TfgU8vkX55+RLwqP1UxEZf3eAAAAAElFTkSuQmCC \n");


    }

}
